package com.example.java.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class CustomProducerParameters {
    public static void main(String[] args) {
        Properties properties = new Properties();
        // 基础配置
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "43.139.50.31:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        // 提高吞吐的关键参数优化
        properties.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);           // 批次大小：16KB
        properties.put(ProducerConfig.LINGER_MS_CONFIG, 5);                // 等待时间：5ms
        properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 64 * 1024 * 1024L); // 缓冲区大小：64MB
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");  // 使用 snappy 压缩

        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);

        // 发送消息
        kafkaProducer.send(new ProducerRecord<>("producer3", "Hello, I am CustomProducerParameters !"), (recordMetadata, exception) -> {
            if (exception == null) {
                System.out.println("主题:" + recordMetadata.topic() + " -> 分区:" + recordMetadata.partition());
                System.out.println("发送成功！");
            } else {
                exception.printStackTrace();
            }
        });

        // 关闭生产者
        kafkaProducer.close();
    }
}